package com.Hermes.NSP;

import com.Hermes.Omega.PK;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.ElementPowPreProcessing;

import java.math.BigInteger;
import java.security.SecureRandom;

public class EncVecTools {
    private static PK pk;
    private static ElementPowPreProcessing h1;
//    private

    public static Element ENCS_SD_SP(EncVec esd, EncVec esp) {
        Element first = pk.getPair( esp.getEvec()[0],esd.getEvec()[0]).getImmutable();//初始化为类的全局变量
        Element second = pk.getPair(esp.getEvec()[1],esd.getEvec()[1]).getImmutable();
//        Element h1 = pk.getH1().getImmutable();//可以加速
        byte[] r2b = new byte[32], r3b = new byte[32];
        SecureRandom rng = new SecureRandom(r2b);
        rng.nextBytes(r2b);
        rng.nextBytes(r3b);
        BigInteger r2 = new BigInteger(r2b), r3 = new BigInteger(r3b);
        Element h2 = h1.pow(r2).getImmutable(), h3 = h1.pow(r3).getImmutable();
        Element gh1 = first.mul(h2).getImmutable();
        Element gh2 = second.mul(h3).getImmutable();
        Element res = gh1.mul(gh2).getImmutable();
        return res.getImmutable();
    }


    public static Element Enum_P_SD(EncNode p1, EncNode p2, EncVec esd) {
        EncVec ep2p1 = new EncVec(p2, p1);
        Element first = pk.getPair(ep2p1.getEvec()[0], esd.getEvec()[0]).getImmutable();
        Element second = pk.getPair(ep2p1.getEvec()[1], esd.getEvec()[1]).getImmutable();
//        Element h1 = pk.getH1().getImmutable();
        byte[] r2b = new byte[32], r3b = new byte[32];
        SecureRandom rng = new SecureRandom(r2b);
        rng.nextBytes(r2b);
        rng.nextBytes(r3b);
        BigInteger r2 = new BigInteger(r2b), r3 = new BigInteger(r3b);
        Element h2 = h1.pow(r2).getImmutable(), h3 = h1.pow(r3).getImmutable();
        Element gh1 = first.mul(h2).getImmutable();
        Element gh2 = second.mul(h3).getImmutable();
        Element res = gh1.mul(gh2).getImmutable();
        return res.getImmutable();
    }
    public static EncVec getOV(EncNode s,EncNode d){
        Element sy = s.getEy().getImmutable();
        Element sx = s.getEx().getImmutable();
        Element dx = d.getEx().getImmutable();
        Element dy = d.getEy().getImmutable();
        return new EncVec(dy.div(sy).getImmutable(),sx.div(dx.getImmutable()));
    }

    public static void setPk(PK pk) {
        EncVecTools.pk = pk;
        h1=pk.getH1().getElementPowPreProcessing();
    }
}
